package com.tank.dwr;

import javax.annotation.Resource;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ScriptSessions;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.stereotype.Controller;

import com.tank.bean.msg.PmContent;
import com.tank.core.TankModel;
import com.tank.service.PmService;

@RemoteProxy(name="PM")
@Controller("PMACTION")
public class PmAction {
	
	@Resource(name="pmService")
	PmService service;
	TankModel tm;

	
	
	public TankModel trackers() throws Exception {
		tm=service.trackers();
		return tm.newInstance();
	}
	
	public TankModel dialog(Integer id) throws Exception {
		try{
			tm=service.dialog(id);
			//tm.printData();
		}catch(Exception e){
			e.printStackTrace();
		}
		return tm.newInstance();
	}
	
	public TankModel send(PmContent pc){
		tm=TankModel.newInstance();
		if(pc== null || pc.getReceiptor() == null ){
			tm.setSuccess(false);
			tm.setMessage("有问题！");
			return tm;
		}
		tm=service.send(pc);
		if(tm.isSuccess()) pushPm(pc);
		return tm;
	}
	
	
	
	public void pushPm(final PmContent pc) {
		
		String page=WebContextFactory.get().getContextPath()+"/pmdialog?id="+pc.getDialog().getId();
		
		ScriptSessionFilter filter=new ScriptSessionFilter(){
			public boolean match(ScriptSession ss) {
				Object id=ss.getAttribute("dialog.id");
				if(id!=null){
					return pc.getDialog().getId().equals((Integer)id);
				}
				return false;
			};
		};
		
		Runnable task=new Runnable() {
			
			public void run() {
				ScriptSessions.addFunctionCall("update", pc);
			}
		};
		Browser.withPageFiltered(page, filter,task );
		
	}

	public boolean removeContent(PmContent pc) throws Exception {
		
		
		if(service.removeContent(pc.getDialog().getId(), pc.getId())){
			
		}
		return true;
	}

	public boolean removeBatch(Integer id) throws Exception {
		if(service.removeBatch(id)){
			
		}
		return true;
	}
	
	public void turnOn(Integer id){
		
		ScriptSession ss=WebContextFactory.get().getScriptSession();
		ss.setAttribute("dialog.id", id);
	}
	
	public void turnOff(){
		ScriptSession ss=WebContextFactory.get().getScriptSession();
		ss.setAttribute("dialog.id", 0);
	}
	

	
	
	
	
	






	
}
